using RestSharp;

namespace Ln.Fram.Core.RestSharp;

public class RestManager
{
	#region 构造函数
	private RestManager(string url, string addr, Method method)
	{
		Client = new RestClient(url);
		Request = new RestRequest(addr, method);
	}
	#endregion

	#region 成员属性
	private RestClient Client { get; set; }
	private RestRequest Request { get; set; }
	#endregion

	#region 自身方法
	public static RestManager Create(string url, string addr, Method method)
	{
		return new RestManager(url, addr, method);
	}

	public RestManager AddBody(object obj)
	{
		Request.AddBody(obj);
		return this;
	}

	public RestManager AddJsonBody(string json)
	{
		Request.AddJsonBody(json);
		return this;
	}

	public RestManager AddHeader(string key, string value)
	{
		Request.AddHeader(key, value);
		return this;
	}

	public RestManager AddHeaders(string[] keys, string[] values)
	{
		if (keys.Length > 0 && keys.Length == values.Length)
		{
			for (int i = 0; i < keys.Length; i++)
				AddHeader(keys[i], values[i]);
		}
		else
		{
			throw new UserFriendlyException("参数不正确！");
		}
		return this;
	}

	public RestManager AddParameter(string key, string value)
	{
		Request.AddParameter(key, value);
		return this;
	}

	public RestManager AddParameters(string[] keys, string[] values)
	{
		if (keys.Length > 0 && keys.Length == values.Length)
		{
			for (int i = 0; i < keys.Length; i++)
				AddParameter(keys[i], values[i]);
		}
		else
		{
			throw new UserFriendlyException("参数不正确！");
		}
		return this;
	}

	public async Task<TOutputDto> ExecuteAsync<TOutputDto>()
	{
		var res = await Client.ExecuteAsync<TOutputDto>(Request);
		return await Task.FromResult<TOutputDto>(res.Data);
	}
	#endregion
}